﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using NetDimension.Weibo;
using System.Net;
using System.IO;
using System.Web;

namespace WCFServiceWebRole1
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码、svc 和配置文件中的类名“Service1”。
    // 注意: 为了启动 WCF 测试客户端以测试此服务，请在解决方案资源管理器中选择 Service1.svc 或 Service1.svc.cs，然后开始调试。
    public class Service1 : IService1
    {
        private static NetDimension.Weibo.OAuth oauth;
        public static NetDimension.Weibo.Client Sina;
        public static string AUTHORIZE_URL;
        public static string CallbackUrl = "https://api.weibo.com/oauth2/default.html";
        public static string AppKey = "3257942575";
        public static string passport = "cbwang505@hotmail.com";
        public static string password = "wcb110120";
        public static string codeout;

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
        public string startoauth()
        {
            oauth = new OAuth("3257942575", "c9990e1d462e41daa44949cf2d64f9fc", "https://api.weibo.com/oauth2/default.html");
            // bool bl = oauth.ClientLogin("cbwang505@hotmail.com", "wcb110120");

            string authorizeUrl = oauth.GetAuthorizeURL();


            return HttpUtility.UrlDecode(authorizeUrl).ToString();
        }
        public string getaccess(string code)
        {
             try
            {
               // oauth = new OAuth("3257942575", "c9990e1d462e41daa44949cf2d64f9fc", "https://api.weibo.com/oauth2/default.html");
                // bool bl = oauth.ClientLogin("cbwang505@hotmail.com", "wcb110120");

                string authorizeUrl = oauth.GetAuthorizeURL();

                AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(code);
            }
            catch (WeiboException ex)
            {
               return ex.Message.ToString();
            }
            if (string.IsNullOrEmpty(oauth.AccessToken))
            {

                return "AccessTokennullexception";

            }
           
        Sina = new NetDimension.Weibo.Client(oauth);
            StringBuilder statusBuilder = new StringBuilder();
            var json = Sina.API.Entity.Statuses.FriendsTimeline(count:20);
            if (json.Statuses != null)
            {
                return "accesssuccess";
            }
            else 
            {
                return "accessfailed";
            }
        }
        public string postweibo(string postmessage)
        {
            try
            {
                //Sina = new NetDimension.Weibo.Client(oauth);
                Sina.API.Entity.Statuses.Update(postmessage, 0, 0, null);
                return "postsuccess";
            }
            catch (Exception ex)
            {

                return ex.Message.ToString();


            }
        }
        public string refresh()
        {
           // Sina = new NetDimension.Weibo.Client(oauth);
            StringBuilder statusBuilder = new StringBuilder();
            var json = Sina.API.Entity.Statuses.FriendsTimeline(count: 20);
            if (json.Statuses != null)
            {
                return "accesssuccess";
            }
            else
            {
                return "accessfailed";
            }
        }
        public string startoneclick()
        {
            oauth = new OAuth("3257942575", "c9990e1d462e41daa44949cf2d64f9fc", "https://api.weibo.com/oauth2/default.html");
            // bool bl = oauth.ClientLogin("cbwang505@hotmail.com", "wcb110120");
            
           AUTHORIZE_URL = oauth.GetAuthorizeURL();
           CookieContainer MyCookieContainer = new CookieContainer();
           HttpWebRequest http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
           http.Referer = AUTHORIZE_URL;
           http.Method = "POST";
           http.ContentType = "application/x-www-form-urlencoded";
           http.AllowAutoRedirect = true;
           http.KeepAlive = true;
           http.CookieContainer = MyCookieContainer;
           string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl) ? "" : CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
           byte[] postData = Encoding.Default.GetBytes(postBody);
           http.ContentLength = postData.Length;

           using (Stream request = http.GetRequestStream())
           {
               try
               {
                   request.Write(postData, 0, postData.Length);
               }
               catch
               {
                   throw;
               }
               finally
               {
                   request.Close();
               }
           }
           string code = string.Empty;
           try
           {
               using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
               {
                   if (response != null)
                   {
                       string codeuri = response.ResponseUri.ToString();
                       codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
                      

                   }
                   response.Close();
               }
           }
           catch (System.Net.WebException)
           {
               throw;
           }

           // string codeuri = webBrowser1.Url.ToString();
           //// richTextBox1.Text += codeuri;
           // string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
           
           try
           {
               AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(codeout);
           }
           catch (WeiboException ex)
           {
               Console.WriteLine(ex.Message);
           }
           if (string.IsNullOrEmpty(oauth.AccessToken))
           {

               return "AccessTokennullexception";

           }
           Sina = new NetDimension.Weibo.Client(oauth);
           StringBuilder statusBuilder = new StringBuilder();
           var json = Sina.API.Entity.Statuses.FriendsTimeline(count: 20);
           if (json.Statuses != null)
           {
               return "accesssuccess";
           }
           else
           {
               return "accessfailed";
           }
        }
        public string startwithoption(string AppKey1, string AppSecret1, string passport1, string password1)
        {
            oauth = new OAuth(AppKey1,AppSecret1, "https://api.weibo.com/oauth2/default.html");
         
            password = password1;
            passport = passport1;
            AUTHORIZE_URL = oauth.GetAuthorizeURL();
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
            http.Referer = AUTHORIZE_URL;
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl) ? "" : CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http.ContentLength = postData.Length;

            using (Stream request = http.GetRequestStream())
            {
                try
                {
                    request.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request.Close();
                }
            }
            string code = string.Empty;
            try
            {
                using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        string codeuri = response.ResponseUri.ToString();
                        codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);


                    }
                    response.Close();
                }
            }
            catch (System.Net.WebException)
            {
                throw;
            }

            // string codeuri = webBrowser1.Url.ToString();
            //// richTextBox1.Text += codeuri;
            // string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);

            try
            {
                AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(codeout);
            }
            catch (WeiboException ex)
            {
                Console.WriteLine(ex.Message);
            }
            if (string.IsNullOrEmpty(oauth.AccessToken))
            {

                return "AccessTokennullexception";

            }
            Sina = new NetDimension.Weibo.Client(oauth);
            StringBuilder statusBuilder = new StringBuilder();
            var json = Sina.API.Entity.Statuses.FriendsTimeline(count: 20);
            if (json.Statuses != null)
            {
                return "accesssuccess";
            }
            else
            {
                return "accessfailed";
            }
        }
    }
}
